package com.shangsheng.security;

import com.shangsheng.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.*;

@Component("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{

    public UserDetails loadUserByUsername(String ssoId) throws UsernameNotFoundException {
        //从数据库获取，这里的ssoId为用户名，就是前端登录的用户名
        User user=xx.find(ssoId);
        if (user==null){
            throw new UsernameNotFoundException("Username not found");
        }
        return new org.springframework.security.core.userdetails.User(user.getSsoId(), user.getPassword(),
                true, true, true, true,
                getGrantedAuthorities(user));
    }

    private List<GrantedAuthority> getGrantedAuthorities(User user){
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        //UserProfile实体对象
        for(UserProfile userProfile : user.getUserProfiles()){
            logger.info("UserProfile : {}", userProfile);
            //添加用户的权限名
            authorities.add(new SimpleGrantedAuthority(userProfile.getType()));
        }
        return authorities;
    }
}
